<template>
  <div class="settings-container">
    <div class="settings-header">
      <h1 class="page-title">系统设置</h1>
      <p class="page-subtitle">管理系统配置和参数</p>
    </div>

    <!-- 概览：当前基础信息 -->
    <el-card shadow="never" class="overview-card">
      <el-descriptions title="当前基础信息概览" :column="3" size="small" border>
        <el-descriptions-item label="网站名称">
          {{ settings.basic.siteName || "未设置" }}
        </el-descriptions-item>
        <el-descriptions-item label="网站地址">
          {{ settings.basic.siteUrl || "未设置" }}
        </el-descriptions-item>
        <el-descriptions-item label="时区">
          <el-tag type="info" round>
            {{ settings.basic.timezone }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-row :gutter="16" class="settings-grid">
      <!-- 左侧菜单 -->
      <el-col :xs="24" :sm="8" :md="6" :lg="6">
        <el-card shadow="always" class="menu-card">
          <el-menu :default-active="activeMenu" class="el-menu-vertical" @select="onSelectMenu">
            <el-menu-item v-for="menu in settingsMenus" :key="menu.key" :index="menu.key">
              <span>{{ menu.name }}</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>

      <!-- 右侧内容 -->
      <el-col :xs="24" :sm="16" :md="18" :lg="18">
        <el-card shadow="always">
          <template #header>
            <div class="card-header">
              <span>{{ getCurrentMenuName() }}</span>
            </div>
          </template>

          <!-- 基本设置 -->
          <div v-if="activeMenu === 'basic'" class="settings-section">
            <el-alert title="基础信息会影响系统的展示与链接生成，请确保准确性。" type="info" show-icon class="mb-16" />
            <el-form :model="settings.basic" label-width="110px">
              <el-row :gutter="16">
                <el-col :xs="24" :md="12">
                  <el-form-item label="网站名称" prop="siteName">
                    <el-input v-model="settings.basic.siteName" placeholder="请输入网站名称" clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="网站地址" prop="siteUrl">
                    <el-input v-model="settings.basic.siteUrl" placeholder="请输入网站地址" clearable />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="网站描述" prop="siteDescription">
                <el-input
                  v-model="settings.basic.siteDescription"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入网站描述"
                  clearable
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>

              <el-row :gutter="16">
                <el-col :xs="24" :md="12">
                  <el-form-item label="管理员邮箱" prop="adminEmail">
                    <el-input v-model="settings.basic.adminEmail" placeholder="请输入管理员邮箱" clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="时区" prop="timezone">
                    <el-select v-model="settings.basic.timezone" placeholder="请选择时区" filterable>
                      <el-option label="Asia/Shanghai" value="Asia/Shanghai" />
                      <el-option label="UTC" value="UTC" />
                      <el-option label="America/New_York" value="America/New_York" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 邮件设置 -->
          <div v-if="activeMenu === 'email'" class="settings-section">
            <el-alert
              title="请确保SMTP配置正确，建议使用独立的发信账户并启用安全传输。"
              type="warning"
              show-icon
              class="mb-16"
            />
            <el-form :model="settings.email" label-width="110px">
              <el-row :gutter="16">
                <el-col :xs="24" :md="12">
                  <el-form-item label="SMTP 服务器" prop="smtpHost">
                    <el-input v-model="settings.email.smtpHost" placeholder="请输入SMTP服务器地址" clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="SMTP 端口" prop="smtpPort">
                    <el-input-number
                      v-model="settings.email.smtpPort"
                      :min="1"
                      :max="65535"
                      controls-position="right"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="16">
                <el-col :xs="24" :md="12">
                  <el-form-item label="用户名" prop="smtpUsername">
                    <el-input v-model="settings.email.smtpUsername" placeholder="请输入SMTP用户名" clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="密码" prop="smtpPassword">
                    <el-input
                      v-model="settings.email.smtpPassword"
                      type="password"
                      show-password
                      placeholder="请输入SMTP密码"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="启用 SSL" prop="smtpSsl">
                <el-switch v-model="settings.email.smtpSsl" />
                <span class="form-help ml-8">若服务端要求TLS/SSL，请开启此选项。</span>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" plain @click="testEmail"> 测试邮件发送 </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 安全设置 -->
          <div v-if="activeMenu === 'security'" class="settings-section">
            <el-alert
              title="建议启用强密码策略与双因素认证，以提升账户安全性。"
              type="success"
              show-icon
              class="mb-16"
            />
            <el-form :model="settings.security" label-width="110px">
              <el-form-item label="密码策略">
                <el-checkbox v-model="settings.security.requireUppercase">要求包含大写字母</el-checkbox>
                <el-checkbox v-model="settings.security.requireNumbers">要求包含数字</el-checkbox>
                <el-checkbox v-model="settings.security.requireSpecialChars">要求包含特殊字符</el-checkbox>
              </el-form-item>

              <el-row :gutter="16">
                <el-col :xs="24" :md="12">
                  <el-form-item label="最小密码长度" prop="minPasswordLength">
                    <el-input-number
                      v-model="settings.security.minPasswordLength"
                      :min="6"
                      :max="32"
                      controls-position="right"
                    />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="会话超时（分钟）" prop="sessionTimeout">
                    <el-input-number
                      v-model="settings.security.sessionTimeout"
                      :min="5"
                      :max="1440"
                      controls-position="right"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="双因素认证" prop="enableTwoFactor">
                <el-switch v-model="settings.security.enableTwoFactor" />
                <span class="form-help ml-8">启用后登录需要额外验证，提高安全性。</span>
              </el-form-item>
            </el-form>
          </div>

          <!-- 应用设置 -->
          <div v-if="activeMenu === 'app'" class="settings-section">
            <el-form :model="settings.app" label-width="120px">
              <el-row :gutter="16">
                <el-col :xs="24" :md="12">
                  <el-form-item label="语言" prop="locale">
                    <el-select v-model="settings.app.locale" placeholder="请选择语言">
                      <el-option label="简体中文 (zh-CN)" value="zh-CN" />
                      <el-option label="English (en-US)" value="en-US" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="分页大小" prop="pageSize">
                    <el-select v-model="settings.app.pageSize" placeholder="请选择分页大小">
                      <el-option v-for="n in [10, 20, 30, 50]" :key="n" :label="n + ' 条/页'" :value="n" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="16">
                <el-col :xs="24" :md="12">
                  <el-form-item label="日期格式" prop="dateFormat">
                    <el-select v-model="settings.app.dateFormat" placeholder="请选择日期格式">
                      <el-option label="YYYY-MM-DD" value="YYYY-MM-DD" />
                      <el-option label="YYYY/MM/DD" value="YYYY/MM/DD" />
                      <el-option label="DD-MM-YYYY" value="DD-MM-YYYY" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :md="12">
                  <el-form-item label="主题色" prop="primaryColor">
                    <el-color-picker v-model="settings.app.primaryColor" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="暗色模式" prop="darkMode">
                <el-switch v-model="settings.app.darkMode" />
              </el-form-item>

              <el-form-item label="通知" prop="notificationsEnabled">
                <el-switch v-model="settings.app.notificationsEnabled" />
              </el-form-item>
            </el-form>
          </div>

          <!-- 存储设置 -->
          <div v-if="activeMenu === 'storage'" class="settings-section">
            <el-form :model="settings.storage" label-width="110px">
              <el-form-item label="存储类型" prop="storageType">
                <el-select v-model="settings.storage.storageType" placeholder="请选择存储类型">
                  <el-option label="本地存储" value="local" />
                  <el-option label="阿里云 OSS" value="oss" />
                  <el-option label="腾讯云 COS" value="cos" />
                  <el-option label="Amazon S3" value="s3" />
                </el-select>
              </el-form-item>

              <template v-if="settings.storage.storageType !== 'local'">
                <el-row :gutter="16">
                  <el-col :xs="24" :md="12">
                    <el-form-item label="Access Key" prop="accessKey">
                      <el-input v-model="settings.storage.accessKey" placeholder="请输入Access Key" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :md="12">
                    <el-form-item label="Secret Key" prop="secretKey">
                      <el-input
                        v-model="settings.storage.secretKey"
                        type="password"
                        show-password
                        placeholder="请输入Secret Key"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="16">
                  <el-col :xs="24" :md="12">
                    <el-form-item label="存储桶" prop="bucket">
                      <el-input v-model="settings.storage.bucket" placeholder="请输入存储桶名称" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :md="12">
                    <el-form-item label="区域" prop="region">
                      <el-input v-model="settings.storage.region" placeholder="请输入区域" clearable />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>

              <el-form-item>
                <el-button type="primary" plain @click="testStorage"> 测试存储连接 </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 保存按钮 -->
          <div class="actions-section">
            <el-divider />
            <el-space wrap>
              <el-button type="primary" @click="saveSettings"> 保存设置 </el-button>
              <el-button @click="resetSettings">重置</el-button>
            </el-space>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

defineOptions({
  name: "SettingsView",
});

const activeMenu = ref("basic");
const settingsMenus = ref([
  { key: "basic", name: "基本设置" },
  { key: "email", name: "邮件设置" },
  { key: "security", name: "安全设置" },
  { key: "app", name: "应用设置" },
  { key: "storage", name: "存储设置" },
]);

const settings = reactive({
  basic: {
    siteName: "NestJS 学习项目",
    siteUrl: "https://example.com",
    siteDescription: "基于 NestJS 和 Vue 3 的学习项目",
    adminEmail: "admin@example.com",
    timezone: "Asia/Shanghai",
  },
  email: {
    smtpHost: "smtp.example.com",
    smtpPort: 587,
    smtpUsername: "",
    smtpPassword: "",
    smtpSsl: true,
  },
  security: {
    requireUppercase: true,
    requireNumbers: true,
    requireSpecialChars: false,
    minPasswordLength: 8,
    sessionTimeout: 30,
    enableTwoFactor: false,
  },
  storage: {
    storageType: "local",
    accessKey: "",
    secretKey: "",
    bucket: "",
    region: "",
  },
  app: {
    locale: "zh-CN",
    darkMode: false,
    pageSize: 10,
    dateFormat: "YYYY-MM-DD",
    notificationsEnabled: true,
    primaryColor: "#409EFF",
  },
});

// 表单引用
const basicFormRef = ref();
const emailFormRef = ref();
const securityFormRef = ref();
const storageFormRef = ref();
const appFormRef = ref();

// 加载态
const emailTesting = ref(false);
const storageTesting = ref(false);

// 校验规则（基础校验）
const rulesBasic = {
  siteName: [{ required: true, message: "请输入网站名称", trigger: "blur" }],
  siteUrl: [
    { required: true, message: "请输入网站地址", trigger: "blur" },
    { type: "url", message: "请输入合法的URL", trigger: ["blur", "change"] },
  ],
  adminEmail: [
    { required: true, message: "请输入管理员邮箱", trigger: "blur" },
    { type: "email", message: "请输入合法的邮箱地址", trigger: ["blur", "change"] },
  ],
  siteDescription: [{ min: 0, max: 200, message: "不超过200字", trigger: "blur" }],
  timezone: [{ required: true, message: "请选择时区", trigger: "change" }],
};

const rulesEmail = {
  smtpHost: [{ required: true, message: "请输入SMTP服务器地址", trigger: "blur" }],
  smtpPort: [{ required: true, message: "请输入SMTP端口", trigger: "change" }],
  smtpUsername: [{ required: true, message: "请输入SMTP用户名", trigger: "blur" }],
  smtpPassword: [{ required: true, message: "请输入SMTP密码", trigger: "blur" }],
};

const rulesSecurity = {
  minPasswordLength: [{ required: true, message: "请输入最小密码长度", trigger: "change" }],
  sessionTimeout: [{ required: true, message: "请输入会话超时时间", trigger: "change" }],
};

const rulesStorage = {
  storageType: [{ required: true, message: "请选择存储类型", trigger: "change" }],
  accessKey: [
    { required: () => settings.storage.storageType !== "local", message: "请输入Access Key", trigger: "blur" },
  ],
  secretKey: [
    { required: () => settings.storage.storageType !== "local", message: "请输入Secret Key", trigger: "blur" },
  ],
  bucket: [{ required: () => settings.storage.storageType !== "local", message: "请输入存储桶名称", trigger: "blur" }],
  region: [{ required: () => settings.storage.storageType !== "local", message: "请输入区域", trigger: "blur" }],
};

const rulesApp = {
  locale: [{ required: true, message: "请选择语言", trigger: "change" }],
  pageSize: [{ required: true, message: "请选择分页大小", trigger: "change" }],
  dateFormat: [{ required: true, message: "请选择日期格式", trigger: "change" }],
  primaryColor: [{ required: true, message: "请选择主题色", trigger: "change" }],
};

const getCurrentMenuName = () => {
  const menu = settingsMenus.value.find((m) => m.key === activeMenu.value);
  return menu ? menu.name : "";
};
const onSelectMenu = (key: string) => {
  activeMenu.value = key;
};

const testEmail = async () => {
  emailTesting.value = true;
  try {
    await new Promise((r) => setTimeout(r, 800));
    ElMessage.success("已触发邮件发送测试");
  } catch (e) {
    ElMessage.error("邮件测试失败，请检查配置");
  } finally {
    emailTesting.value = false;
  }
};
const testStorage = async () => {
  storageTesting.value = true;
  try {
    await new Promise((r) => setTimeout(r, 800));
    ElMessage.success("已触发存储连接测试");
  } catch (e) {
    ElMessage.error("存储连接测试失败，请检查配置");
  } finally {
    storageTesting.value = false;
  }
};
const saveSettings = async () => {
  // 逐分区校验，通过后再保存
  const forms = [
    basicFormRef.value,
    emailFormRef.value,
    securityFormRef.value,
    appFormRef.value,
    storageFormRef.value,
  ].filter(Boolean);
  let validAll = true;
  for (const form of forms) {
    const ok = await new Promise<boolean>((resolve) => form.validate((v: boolean) => resolve(v)));
    if (!ok) validAll = false;
  }
  if (!validAll) {
    ElMessage.warning("请完善必填项后再保存");
    return;
  }
  console.log("保存设置:", settings);
  ElMessage.success("设置已保存（示例）");
};
const resetSettings = () => {
  // 简化为示例：仅提示
  ElMessage.info("请根据需求实现具体的重置逻辑");
};

onMounted(() => {
  console.log("系统设置页面加载完成");
});
</script>

<style scoped>
.settings-container {
  padding: 24px;
  background-color: #f8f9fc;
  min-height: 100vh;
}

.settings-header {
  margin-bottom: 16px;
}
.page-title {
  color: #5a5c69;
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 6px;
}
.page-subtitle {
  color: #858796;
  margin: 0;
}

.settings-grid {
  margin-top: 8px;
}
.overview-card {
  margin-bottom: 12px;
}
.mb-16 {
  margin-bottom: 16px;
}
.form-help {
  color: #909399;
  font-size: 12px;
}
.ml-8 {
  margin-left: 8px;
}

.menu-card {
  padding: 0;
}

.settings-section {
  min-height: 320px;
}

.actions-section {
  margin-top: 12px;
}
.card-header {
  font-size: 14px;
  color: #606266;
}
</style>
